As with any kind of app, there are difficult issues to solve when we write Node apps. In this article, we’ll look at some solutions to common problems when writing Node apps.
Get the Latest and Oldest Record in Mongoose
We can get the latest document by using the sort
method.
For instance, we can write:
MySchema.find().sort({ _id: -1 }).limit(1)
to get the latest document.
_id
set to -1 means we sort the IDs in descending order.
To get the oldest document, we can write:
MySchema.find().sort({ _id: 1 }).limit(1)
_id
set to 1 means we sort the IDs in ascending order.
limit
limits the entries returned.
Add 1 Month from Now to Current Date in moment.js
We can add 1 month from now with monent.js with the add
method.
For instance, we can write:
moment().add(1, 'months').calendar();
moment
returns the current date and time.
We just call add
with the quantity and the unit that we want to add to add what we want to the date.
Also, we can replace 'months'
with 'days'
and 'years'
to add those quantities as well.
Convert Native Promise to a Bluebird
We can call Blurbird’s resolve
method to convert a native promise to a Bluebird promise.
For example, we can write:
Promise.resolve(somePromise())
where somePromise
is a function that returns a native ES6 promise.
Get “HTTP_REFERER” with NodeJS
If we use the http
module to create our HTTP server, we can use the req.headers.referer
to get the HTTP_REFERER
header from the request.
For instance, we can write:
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req.headers.referer);
})
JavaScript Asynchronous Constructor
We can create static async
methods in JavaScript classes, so we can use that to create methods that returns a promise with a resolved value we want.
For instance, we can write:
class Person{
constructor(name){
this.age = 5;
this.name = name;
return new Promise((resolve) => {
resolve(this);
});
};
}
We have the Person
constructor which returns a promise.
If we return something in the constructor
, then it’ll be returned instead of returning the instance directly.
We returned a promise that resolves to the Person
instance, so we can call then
to get the resolved result.
Then we can call then
on it by writing:
new Person('james')
.then((instance) => {
//...
});
instance
has the Person
instance, and we can do what we like with it.
Using Babel Register with require(‘babel/register’)
To use Babel in our app without any transportation, we can use the babel/register
package.
We add the package on top of our script, then we can use the features supported by the preset.
To use it, we run:
npm install @babel/core @babel/register --save-dev
to install @babel/core
and @babel/register
to add Babel Register.
Then to use it, we can write:
require("@babel/register");
const env = process.env.NODE_ENV || 'development';
const port = process.env.NODE_PORT || 8888;
const http = require('http');
const express = require('express');
const app = express();
app.set('port', port);
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => {
res.send('hello!');
});
http.createServer(app).listen(app.get('port'), () => {
console.info('app started');
});
We require the babel-register
package at the top of the script.
Then we run our Express apps with the latest features below it.
Now the Express app is transpiled on the fly.
Also, we can add babel-cli
to our project instead of using Babel Register, which is faster since it doesn’t do on-the-fly transpilation.
To do that, we can run:
npm install --save-dev @babel/core @babel/node
to install the Babel packages.
Then we can run babel-node
in our app:
npx babel-node app.js
Then we can write:
app.js
const env = process.env.NODE_ENV || 'development';
const port = process.env.NODE_PORT || 8888;
const http = require('http');
const express = require('express');
const app = express();
app.set('port', port);
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => {
res.send('hello!');
});
http.createServer(app).listen(app.get('port'), () => {
console.info('app started');
});
and it’ll run properly since we’re using Babel to transpile the app.
Conclusion
We can get the oldest and latest records with Mongoose easily. Also, we can use Babel Register or Babel Node to run our app. We can return anything in our constructor including promises, so we can use that to create an async constructor. We can get the HTTP referer from the headers. Native promises can be converted to Bluebird promises.